var webSocket = null;
var tryTime = 0;
var debug = false;

	//initSocket();
window.onbeforeunload = function() {
	// 离开页面时的其他操作
	// 监听窗口关闭事件，当窗口关闭时，主动去关闭websocket连接，防止连接还没断开就关闭窗口，server端会抛异常。
	if(webSocket!=null){
		webSocket.close();
	}
};

/**
 * 初始化websocket，建立连接
 */
var timeout;
function initSocket(relation) {
	
	//操作提示
	var show=function(msg,addclass){
		var  message =  $("#messageWrap");
		message.html(msg);
		if(addclass){
			message.removeAttr("class").addClass(addclass);
		}
		
		if(timeout){
			clearTimeout(timeout);
		}
		
		timeout = setTimeout(function(){
			showold();
		},3000);
	}
	
	var notice=null;
	var showMsg=function(msg,name,code){
		if(code==2){
			if(notice!=null){
				notice.close();
				notice=null;
			}
			
			setTimeout(function(){
				notice = art.dialog.notice({
				    title: "from: "+name,
				    width: 220,// 必须指定一个像素宽度值或者百分比，否则浏览器窗口改变可能导致artDialog收缩
				    content: "<a href='#' onclick='return online()' >"+msg+"</a>",
				    time: 0,
				    close:function(){
				    	notice=null;
				    }
				});	
			},900)
			
		}
		
		try{
			//调用online的,
			appendOther(msg,name);
		}catch(e){}
	}
	
	
	var showold=function(msg,addclass){
		var  message =  $("#messageWrap");
		message.removeAttr("class");
		message.html(message.attr("old"));
	}
	
	
	if (!window.WebSocket) {
		return false;
	}

	webSocket = new WebSocket("ws://"+basepath+"/ws/"+relation+"/"+adminid+"/websocket.do");

	// 收到服务端消息
	webSocket.onmessage = function(msg) {
		var data = eval('(' + msg.data + ')');
		var code = data.code;
		var message = data.msg;
		
		if(code==0){
			show(message,"progress-bar progress-bar-info progress-bar-striped");
		}else if(code==1||code==2){
			var fromname = data.from;
			showMsg(message,fromname,code);
		}
		
	};

	// 异常
	webSocket.onerror = function(event) {
		console.log(event);
		show("连接错误","progress-bar progress-bar-success progress-bar-striped");
	};

	// 建立连接
	webSocket.onopen = function(event) {
		show("建立连接","progress-bar progress-bar-success progress-bar-striped");
	};

	// 断线重连
	webSocket.onclose = function() {
		show("连接已经关闭","progress-bar progress-bar-success progress-bar-striped");
		 // 2秒后重连
		 setTimeout(function(){
			 if(webSocket = null){
				 initSocket("test");
			 }
		 }, 2000);
	};
	
}



// 关闭连接
function closeWebSocket() {
	if(webSocket!=null){
		webSocket.close();
	}
	webSocket=null;
}

//刷新连接,先断后开



// 发送消息
function sendSocket() {
	var message = "test message!";
	webSocket.send(message);
}